<template>
	<div>
		<ProTable ref="proTable" title="账号管理" :columns="columns" :request-api="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="mb16">
					<el-button type="primary" @click="toUpdate()" v-auth="'system:account:create:invoke'"> 新增账号 </el-button>
				</div>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<template #operation="{ row }">
				<el-button type="primary" link v-if="!row.isAdmin" v-auth="'system:account:reset-pwd:invoke'" @click="onChangePwd(row)"> 重置密码 </el-button>
				<el-divider direction="vertical" v-if="!row.isAdmin" v-auth="'system:account:reset-pwd:invoke'" />
				<el-button type="primary" link v-if="!row.isAdmin" v-auth="'system:account:edit:invoke'" @click="toUpdate(row)"> 编辑 </el-button>
				<el-divider direction="vertical" v-if="!row.isAdmin" v-auth="'system:account:edit:invoke'" />
				<el-button type="primary" link v-if="!row.isAdmin" v-auth="'system:account:status:invoke'" @click="changeStatus(row)">
					{{ !row.status ? '禁用' : '启用' }}
				</el-button>
				<el-divider direction="vertical" v-if="!row.isAdmin" v-auth="'system:account:status:invoke'" />
				<el-button type="primary" link v-if="!row.isAdmin" v-auth="'system:account:bind-oa:invoke'" @click="changeOA(row)">
					{{ !row.isopen ? '解绑OA' : '绑定OA' }}
				</el-button>
				<el-divider direction="vertical" v-if="!row.isAdmin" v-auth="'system:account:bind-oa:invoke'" />
				<el-button type="primary" link v-if="!row.isAdmin" v-auth="'system:account:delete:invoke'" @click="onDelete(row)"> 移除 </el-button>
			</template>
		</ProTable>
		<changePwd :visible="changePwdVisible" :row="changePwdRow" @handleClose="closeChangePwd" />
	</div>
</template>

<script setup lang="tsx" name="storeList">
import { onMounted, ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchAccountList, fetchDelAccount, fetchSelectRoleList, fetchAccountStatus } from '/@/api/system';
import { encryptPhoneNumber } from '/@/utils/commonFunction';
import changePwd from './dialog/changePwd.vue';

const router = useRouter();

const changePwdVisible = ref<Boolean>(false);
const changePwdRow = ref<any>();

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'NAME',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
	};

	return fetchAccountList(data);
};

const searchArr = [
	{
		label: '姓名',
		value: 'NAME',
	},
	{
		label: '账号',
		value: 'USERNAME',
	},
];

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'keywords',
		label: '账号搜索',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.searchType}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => {
								scope.searchParam.searchType = value;
							}}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'roleId',
		label: '角色筛选',
		isShow: false,
		minWidth: 100,
		search: { el: 'select', props: { placeholder: '选择角色', clearable: true, filterable: true } },
		fieldNames: { label: 'roleName', value: 'id' },
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchSelectRoleList().then((res: any) => {
					resolve({
						code: 200,
						msg: 'success',
						data: res.data,
					});
				});
			});
		},
	},
	{
		prop: 'username',
		label: '账号',
		minWidth: 180,
		align: 'left',
		render: (scope: any) => {
			return (
				<div>
					{encryptPhoneNumber(scope.row.username)}
					{scope.row.isAdmin && (
						<el-tag type="primary" class="ml5">
							超级管理员
						</el-tag>
					)}
				</div>
			);
		},
	},
	{
		prop: 'nickName',
		label: '名称',
		minWidth: 140,
	},
	{
		prop: 'status',
		label: '账号状态',
		minWidth: 100,
		fieldNames: { label: 'name', value: 'id' },
		enum: [
			{ id: 0, name: '启用' },
			{ id: 1, name: '禁用' },
		],
	},
	{
		prop: 'roleNames',
		label: '角色',
		minWidth: 200,
	},
	{
		prop: 'createTime',
		minWidth: 180,
		label: '创建时间',
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 320, align: 'left' },
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.searchType;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const onChangePwd = (row: any) => {
	changePwdVisible.value = true;
	changePwdRow.value = row;
};

const closeChangePwd = () => {
	changePwdVisible.value = false;
	changePwdRow.value = null;
};

const changeStatus = (row: any) => {
	const isOpen = !row.status;
	ElMessageBox.confirm(`确认${isOpen ? '禁用' : '启用'}该账号?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchAccountStatus({ id: row.id, status: isOpen ? 1 : 0 });
		if (res.code == 200) {
			ElMessage.success(isOpen ? '禁用成功' : '启用成功');
			proTable.value?.getTableList();
		}
	});
};

const resetPwd = (row?: any) => {};

const toUpdate = (row?: any) => {
	router.push(row ? `/system/account/edit/${row.id}` : `/system/account/add`);
};

const changeOA = (row?: any) => {};

const onDelete = async (row: any) => {
	ElMessageBox.confirm('确认移除该账号?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchDelAccount({ id: row.id });
		if (res.code == 200) {
			ElMessage.success('移除成功');
			proTable.value?.getTableList();
		}
	});
};

// 页面加载时
onMounted(() => {
	NextLoading.done();
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
